package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;//假设这是你的数据访问层接口

    @Around("@annotation(com.itheima.anno.LogOperation)")
    public Object recordLog(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();

        //执行目标方法
        Object result = pjp.proceed();

        //计算耗时
        long endTime = System.currentTimeMillis();
        long costTime = endTime - startTime;

        // 构建日志对象实体
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getCurrentUserId()); // 这里需要你根据实际情况获取当前用户 ID
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(pjp.getTarget().getClass().getName());
        operateLog.setMethodName(pjp.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));
        operateLog.setReturnValue(result != null ? result.toString() : "void");
        operateLog.setCostTime(costTime);

        //记录操作日志
        log.info("记录操作日志: {}", operateLog);

        operateLogMapper.insert(operateLog);
        return result;
    }

    private Integer getCurrentUserId() {
        //实现获取当前登录用户的逻辑
        //这个方法需要根据你的安全框架或上下文来实践
        return CurrentHolder.getCurrentId();
    }
}
























